package com.itogis.rest.serivce.Impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itogis.rest.dao.LoginDao;
import com.itogis.rest.po.SysMenuSet;
import com.itogis.rest.po.SysRightInfo;
import com.itogis.rest.po.SysUserInfo;
import com.itogis.rest.po.VoteEvent;
import com.itogis.rest.po.VoteEventGroupTactics;
import com.itogis.rest.po.VoteLog;
import com.itogis.rest.po.VoteOption;
import com.itogis.rest.po.VotePageScript;
import com.itogis.rest.po.VoteResultStat;
import com.itogis.rest.serivce.LoginService;
import com.itogis.util.MD5;

/**
 * 
 * @author Administrator
 * 
 */
@Component
public class LoginServiceImpl implements LoginService {

	@Autowired
	private LoginDao loginDao;

	/**
	 * 登录服务类
	 * 
	 * @param loginid
	 * @param password
	 * @return -2：用户，密码为空 0：用户不存在 1：密码错误 2：登录成功
	 */
	public int login(String loginId, String password) {
		if (loginId == null && password == null) {
			return -2;
		}
		int i = -2;
		boolean bool = loginDao.isExistLoginId(loginId);
		if (!bool) {
			i = 0;
		} else {
			MD5 md5 = new MD5();
			password = md5.getMD5ofStr(password);
			bool = loginDao.checkPassword(loginId, password);
			if (!bool) {
				i = 1;
			} else {
				i = 2;
			}
		}
		return i;
	}

	public int ipLogin(String IP) {
		if (IP == null || IP.equals("127.0.0.11")) {
			return -2;
		}
		int i = -2;
		boolean bool = loginDao.isExistLoginIP(IP);
		if (bool) {
			i = 0;
		} else {
			i = 1;
		}
		return i;
	}

	public VoteEvent getVoteEventByName(String voteEventName) {
		return loginDao.getVoteEventByName(voteEventName);
	}
	public VoteEvent getVoteEventById(Long id) {
		return loginDao.getVoteEventById(id);
	}	
	public VotePageScript getVoteScriptPageById(Long id) {
		return loginDao.getVoteScriptPageById(id);
	}	
	public String selectSQLToPrintTable(String sql) {
		try {
			return loginDao.selectSQLToPrintTable(sql);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}	
	
	
	public List<VoteOption> getVoteOptionByEventId(VoteEvent event,String userId,String userIp) {
		return loginDao.getVoteOptionByEventId(event,userId,userIp);
	}

	public List<VoteResultStat> getVoteResultStatByEventId(Long event_id) {
		return loginDao.getVoteResultStatByEventId(event_id);
	}
	
	public List<VoteResultStat> getVoteResultStatOnLineByEventIds(String eventIds) {
		return loginDao.getVoteResultStatOnLineByEventIds(eventIds);
	}
	
	
	public void submitVote(Long event_id,String[] optionIds,String[] mess,String ip,String userID) throws Exception {
		Date now = new Date();
		VoteEvent voteEvent=this.getVoteEventById(event_id);
		if(!voteEvent.getStatus().equals("NORMAL"))
		{
			throw new Exception("当前投选不允许再进行投票");
		}	
		if (now.before(voteEvent.getStartTime())) {			
			throw new Exception("投票还没有生效,请稍后进行");
		}
		if (now.after(voteEvent.getEndTime())) {			
			throw new Exception("投票已结束,不允许再进行");
		}
		if(voteEvent.getStyle().equals("LOGIN") && userID==null)
		{
			throw new Exception("请先登录，再投票");
		}	
		if(optionIds.length<voteEvent.getMinPoint() || optionIds.length>voteEvent.getMaxPoint())
		{
			throw new Exception(voteEvent.getShowCheckMes());
		}	
		Date lastDate=loginDao.getMaxVoteLogDateByIpOrUserId(event_id,ip,userID);		
		if(voteEvent.getPointType().equals("ONE")&& lastDate!=null)
		{//假如有投票则提示 不允许重复投票
			throw new Exception("已投过票不允许重复投票");
		}
		if(lastDate!=null && getDays(now,lastDate)<voteEvent.getSpaceHour())
		{
			throw new Exception("你已投过票,请休息会再进行投票");
		}
		
		//VoteEventGroupTactics voteEventGroupTactics=loginDao.getVoteEventGroupTacticsById(voteEvent.getVoteGgroupId());
		if(voteEvent.getVoteGgroupId()!=null)
		{
			VoteEventGroupTactics voteEventGroupTactics=loginDao.getVoteEventGroupTacticsByTacticsIdAndUserId(voteEvent.getVoteGgroupId(),userID,ip,voteEvent);
			if(voteEventGroupTactics!=null)
			{
				int num=optionIds.length;
				if(voteEventGroupTactics.getEventAmount()+1>voteEventGroupTactics.getRelGroupMax())
				{
					throw new Exception(" 投票组策略["+voteEventGroupTactics.getDescription()+"] 错误[您当前的投票将超出策略可投票的总组数.]");
				}	
				if(voteEventGroupTactics.getOptionAmount()+num>voteEventGroupTactics.getVoteSumMax())
				{
					throw new Exception(" 投票组策略["+voteEventGroupTactics.getDescription()+"] 错误[您当前的投票将超出策略可投票的总票数.]");
				}	
				//合计最大投票数-已经投票数-本次投票数=剩余投票数
				//合计最大投票组数-已经投票组数-本次投票组数=剩余需要投票组数
				if(voteEventGroupTactics.getVoteSumMax()-voteEventGroupTactics.getOptionAmount()-num<voteEventGroupTactics.getRelGroupMax()-voteEventGroupTactics.getEventAmount()-1)
				{//
					throw new Exception(" 投票组策略["+voteEventGroupTactics.getDescription()+"] 错误[根据策略,您本次投票完后,剩余可投票数就不能完成本次投票策略组数.本次投票完成后您只剩"+(voteEventGroupTactics.getVoteSumMax()-voteEventGroupTactics.getOptionAmount()-num)+"票可投,但还必须再投够"+(voteEventGroupTactics.getRelGroupMax()-voteEventGroupTactics.getEventAmount()-1)+"个组]");
				}	
			}	
		}
		if(voteEvent.getPointType().equals("ONCEMORE"))
		{//覆盖式投票 更新原有投票为无效
			loginDao.updateVoteLogEffact(voteEvent,ip,userID);
		}
		List<VoteOption> voteOptionList=loginDao.getVoteOptionByEventId(voteEvent,userID,ip);
		String message="";
		for (int i = 0; i < optionIds.length; i++) {
			VoteOption voteOptionIn =null;
			for(VoteOption voteOption:voteOptionList)
			{
				if(voteOption.getId().toString().equals(optionIds[i]))
				{
					voteOptionIn=voteOption;
					break;
				}	
			}			
			loginDao.insertVoteLog(voteEvent,voteOptionIn,ip,userID); 				
		}
		message="";
		for (int k = 0; k < mess.length; k++) {
			String[] mes=mess[k].split("~");			
			String optionId=mes[0];
			if(!optionId.equals(""))
			{	
			if(!mes[1].equals("无"))
			{	
			message=mes[1];
			}
			if("Y".equals(voteEvent.getSpeakNone()))
			{//
				loginDao.insertVoteLogMessage(optionId,message,"-1");
			}
			else
			{
				loginDao.insertVoteLogMessage(optionId,message,userID);
			}	
			}
		}
		//得到统计结果
		loginDao.iniVoteResultStat(voteEvent);
	}
    
	public static long getDays(Date date1, Date date2) {	    
	    long day = (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000)*24;
	    return day;
	}
	
	public List<VoteLog> getVoteLogByIpOrUserId(Long event_id,String ip,String user_id) {
		return loginDao.getVoteLogByIpOrUserId(event_id,ip,user_id);
	}
	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.itogis.rest.serivce.LoginService#getMenu(java.lang.String)
	 */
	public List getMenu(String userId) {
		List l = loginDao.getMenu(userId);
		return l;
	}
	
	public List<SysRightInfo> getTreeMenu(String userId) {		
		return loginDao.getTreeMenu(userId);
	}
	public void iniTreeMenuXml(Element root, List<SysRightInfo> ls) {		
		String id=root.attributeValue("id");
		for(SysRightInfo sysRightInfo:ls)
		{
			if(id.equals(String.valueOf(sysRightInfo.getParentId()))&& sysRightInfo.getRightId()!=0)
			{
				if(sysRightInfo.getSonCount()!=0 )
				{//有子的菜单
					Element item = root.addElement("item");  
					item.addAttribute("id", String.valueOf(sysRightInfo.getRightId()));  
					item.addAttribute("text", sysRightInfo.getRightName());  
					item.addAttribute("im0", "dhtmlxtree_icon.gif");  
					item.addAttribute("im1", "dhtmlxtree_icon.gif");  
					item.addAttribute("im2", "dhtmlxtree_icon.gif"); 			
					Element sonItem = item.addElement("userdata"); 
					sonItem.addAttribute("name", "desc").addText(sysRightInfo.getDesc()==null?"无":sysRightInfo.getDesc()); 		
					sonItem = item.addElement("userdata"); 
					sonItem.addAttribute("name", "groupnode").addText("true"); 
					//继续找子菜单
					iniTreeMenuXml(item,ls);
				}
				else
				{//叶子菜单
					Element subItem = root.addElement("item");  
					subItem.addAttribute("id", String.valueOf(sysRightInfo.getRightId()));  
					subItem.addAttribute("text",sysRightInfo.getRightName()); 
					Element sonItem = subItem.addElement("userdata");  
					sonItem.addAttribute("name", "pageid").addText(sysRightInfo.getPageId()); 					
					if(sysRightInfo.getReportId()!=null)
					{	
					sonItem = subItem.addElement("userdata");  
					sonItem.addAttribute("name", "reportid").addText(sysRightInfo.getReportId()); 
					}
					if(sysRightInfo.getParams()!=null)
					{	
					sonItem = subItem.addElement("userdata");  
					sonItem.addAttribute("name", "params").addText(sysRightInfo.getParams()); 
					}
					if(sysRightInfo.getOtherfilename()!=null)
					{	
					sonItem = subItem.addElement("userdata");  
					sonItem.addAttribute("name", "otherfilename").addText(sysRightInfo.getOtherfilename()); 	
					}
					if(sysRightInfo.getConfigfilename()!=null)
					{
					sonItem = subItem.addElement("userdata"); 
					sonItem.addAttribute("name", "configfilename").addText(sysRightInfo.getConfigfilename()); 	
					}
					if(sysRightInfo.getDesc()!=null)
					{
					sonItem = subItem.addElement("userdata"); 
					sonItem.addAttribute("name", "desc").addText(sysRightInfo.getDesc()); 
					}
				}	
			}	
		}	
	}
	
	public List getFunction(String userId) {
		List l = loginDao.getFunction(userId);
		return l;
	}

	public String getUserId(String loginId) {
		return this.loginDao.getUserId(loginId);
	}
	
	public String getWeekWorkByUseId(Long useId,String groupId) {
		return this.loginDao.getWeekWorkByUseId(useId,groupId);
	}
	
	public String getUserName(String loginId) {
		return this.loginDao.getUserName(loginId);
	}
	
	public String getUserKfbm(String loginId) {
		return this.loginDao.getUserKfbm(loginId);
	}
	
	public String getUserdepartment(String loginId) {
		return this.loginDao.getUserdepartment(loginId);
	}

	public SysUserInfo getUserIdByIP(String IP) {
		return this.loginDao.getUserIdByIP(IP);
	}

	public void logout() {

	}

	public boolean updatePassword(String userid, String password) {
		return loginDao.updatePassword(userid, password);
	}
	public boolean updateWeekWork(String userid, String workMes,String groupId) {
		return loginDao.updateWeekWork(userid, workMes,groupId);
	}

	public boolean updateLoginIP(String userid, String IP) {
		return loginDao.updateLoginIP(userid, IP);
	}

	public SysMenuSet getMenuSet() {
		return loginDao.getMenuSet();
	}
}
